﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using VMDS.Business.Entities;
using VMDS.Business.Processes;
using VMDS.Settings;

namespace VMDS.Services.ClientService
{
    class UserDownloader
    {
        private BackgroundWorker worker;
        private FileCopier copier;
        private FastZip arciver;
        private OS _os;
        public OS Os { get { return _os; } }
        private Thread thread;
        private string _currentFile;
        private MainServiceReference.IMainServiceContract ms;
        private TaskDataPack _ti;
        public UserDownloader(MainServiceReference.IMainServiceContract mainService,TaskDataPack ti)
        {
            _ti = ti;
            ms = mainService;
            thread = Thread.CurrentThread;
            worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            copier = new FileCopier();
            copier.CopyProgress += new CopyProgressEventHandler(copier_CopyProgress);
            FastZipEvents events = new FastZipEvents();

            events.Progress += new ProgressHandler(events_Progress);
            events.ProcessFile += new ProcessFileHandler(events_ProcessFile);
            events.ProgressInterval = TimeSpan.FromMilliseconds(500);
            arciver = new FastZip(events);

        }

        void events_ProcessFile(object sender, ScanEventArgs e)
        {
            _ti.CurrentOperation = "распаковка " + e.Name;
            ClientServiceLogic.ChangeTaskInfo(_ti);
        }

        void events_Progress(object sender, ProgressEventArgs e)
        {
             _ti.CurrentProgress = Convert.ToInt32(e.PercentComplete);
            ClientServiceLogic.ChangeTaskInfo(_ti);
        }

        public event EventHandler Completed;



        public void Setup(OS os)
        {
            if (worker.IsBusy) return;
            _os = os;
            worker.RunWorkerAsync();
        }
        void copier_CopyProgress(object sender, CopyProgressEventArgs e)
        {
         // Console.SetCursorPosition(10,10);
           // Console.Write(_currentFile+ " "+ );
            _ti.CurrentProgress = (int) ((e.TotalBytesTransferred*100)/e.TotalFileSize);
            ClientServiceLogic.ChangeTaskInfo(_ti);
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            Logger.WriteLog("Try to setup "+_os.Name);
            string from = "";
            string to = "";
            string local = new ClientConfiguration(@"d:\virtual\data\config.ini").LocalStorage;
            Guid code = Guid.NewGuid();
            try
            {
                from = ms.GetShareUNC();
                if (!Directory.Exists(from))
                {
                    Logger.WriteLog(from + " does not exists", true);
                    return;
                }
            }
            catch
            {

                return;
            }
            from = from + "\\OS\\" + _os.Name;
            to = local + "cache\\" + code;
            try
            {
                Directory.CreateDirectory(to);
            }
            catch
            {
                Logger.WriteLog("Unable to create dir "+to,true);
                return;
            }
            foreach (string file in Directory.EnumerateFiles(from))
            {
                var filename = new System.IO.FileInfo(file).Name;
                _currentFile = filename;
                try
                {
                    Logger.WriteLog("Copying "+file);
                    copier.CopyFile(file, to + "\\" + filename);
                }
                catch(Exception ex)
                {
                    Logger.WriteLog("Copying failed! \n"+ex,true);
                    return;
                }
            }
            try
            {
                Logger.WriteLog("unzipping...");
                arciver.ExtractZip(to + "\\OS.zip", to, "");
            }
            catch (Exception ex)
            {
                Logger.WriteLog("Unzipping failed\n"+ex,true);
                return;
            }
            try
            {
                Logger.WriteLog("Delete temp files");
                File.Delete(to + "\\OS.zip");
                var dest = local + "OS\\" + _os.Name;
                if (Directory.Exists(dest))
                {
                    Directory.Delete(dest, true);
                }

                Directory.Move(to, dest);
                if (Completed!=null) Completed(this,new EventArgs());
                Logger.WriteLog(_os.Name +" was installed");
            }
            catch(Exception ex)
            {
                Logger.WriteLog("Temp clear fail\n"+ex,true);
                return;
            }
            ClientServiceLogic.CompleteOrDeleteTaskInfo(_ti);
        }
        
    }

}
